package com.labtalk.admin.config.component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.labtalk.admin.constant.HttpStatus;
import com.labtalk.admin.pojo.common.ResponseVo;
import com.labtalk.admin.utils.ResponseOutputUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author G-pointy
 * @Date 2022/8/10
 * @Description: 自定义 未登录/token失效 配置类
 */
@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Value("${jwt.header}")
    private String header;

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        if (StringUtils.isEmpty(request.getHeader(header))) {
            ResponseOutputUtil.outputJson(response, ResponseVo.error(HttpStatus.TOKEN_MISSING, "未登录，请登录", null));
            return;
        }
        ResponseVo responseCommon = ResponseVo.error(HttpStatus.UNAUTHORIZED, "未登录或登录超时，请登录", null);
        out.write(new ObjectMapper().writeValueAsString(responseCommon));
        out.flush();
        out.close();
    }
}
